package me.zhengjie.spider.util.pipeline;

import cn.hutool.core.collection.CollectionUtil;
import lombok.Data;
import me.zhengjie.spider.comic.domain.SpiderComic;
import me.zhengjie.spider.comic.domain.SpiderComicDetail;
import me.zhengjie.spider.comic.service.SpiderComicDetailService;
import me.zhengjie.spider.comic.service.SpiderComicService;
import me.zhengjie.spider.common.SpiderConstant;
import me.zhengjie.spider.domain.comic.ComicBean;
import me.zhengjie.spider.domain.comic.ComicRuleBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.List;

@Data
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SpiderComicDetailPipeline implements Pipeline {
    private ComicBean bean;
    private ComicRuleBean ruleBean;
    @Autowired
    private SpiderComicService spiderComicService;
    @Autowired
    private SpiderComicDetailService spiderComicDetailService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void process(ResultItems resultItems, Task task) {
        List<String> tagList = resultItems.get(SpiderConstant.TAG);
        List<String> authorList = resultItems.get(SpiderConstant.AUTHOR);
        String detailHref = resultItems.get(SpiderConstant.DETAIL_HREF);
        if (CollectionUtil.isNotEmpty(tagList)) {
            bean.setTag(CollectionUtil.join(CollectionUtil.filter(tagList, tag -> StringUtils.isNotBlank(tag.trim())), SpiderConstant.SEPARATOR));
        } else {
            bean.setTag(SpiderConstant.DEFAULT_TAG);
        }
        if (CollectionUtil.isNotEmpty(authorList)) {
            bean.setAuthor(CollectionUtil.join(CollectionUtil.filter(authorList, tag -> StringUtils.isNotBlank(tag.trim())), SpiderConstant.SEPARATOR));
        } else {
            bean.setAuthor(SpiderConstant.DEFAULT_AUTHOR);
        }
        SpiderComicDetail spiderComicDetail = new SpiderComicDetail();
        spiderComicDetail.setComicId(bean.getComicId());
        spiderComicDetail.setAlt("1");
        spiderComicDetail.setHref(detailHref);
        spiderComicDetail.setDeletedFlag(false);
        SpiderComic spiderComic = new SpiderComic();
        BeanUtils.copyProperties(bean, spiderComic);
        spiderComicService.update(spiderComic);
        spiderComicDetailService.create(spiderComicDetail);
    }
}
